const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const crypto = require('crypto');
const router = express.Router();

// 导入工具和中间件
const { success, error, badRequest, notFound, forbidden, asyncHandler } = require('../utils/response');
const { authenticateToken } = require('../utils/auth');

// 导入服务层
const uploadService = require('../services/uploadService');

// 导入DAO
const fileDao = require('../dao/fileDao');

// 配置上传目录
const UPLOAD_DIR = process.env.UPLOAD_DIR || './uploads';
const AUDIO_DIR = path.join(UPLOAD_DIR, 'audio');
const VIDEO_DIR = path.join(UPLOAD_DIR, 'video');
const IMAGE_DIR = path.join(UPLOAD_DIR, 'image');

// 确保上传目录存在
async function ensureUploadDirs() {
  try {
    await fs.mkdir(UPLOAD_DIR, { recursive: true });
    await fs.mkdir(AUDIO_DIR, { recursive: true });
    await fs.mkdir(VIDEO_DIR, { recursive: true });
    await fs.mkdir(IMAGE_DIR, { recursive: true });
  } catch (error) {
    console.error('创建上传目录失败:', error);
  }
}

// 初始化上传目录
ensureUploadDirs();

// 配置multer存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    let uploadPath = UPLOAD_DIR;
    
    if (file.mimetype.startsWith('audio/')) {
      uploadPath = AUDIO_DIR;
    } else if (file.mimetype.startsWith('video/')) {
      uploadPath = VIDEO_DIR;
    } else if (file.mimetype.startsWith('image/')) {
      uploadPath = IMAGE_DIR;
    }
    
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    // 生成唯一文件名
    const timestamp = Date.now();
    const randomString = crypto.randomBytes(8).toString('hex');
    const ext = path.extname(file.originalname);
    const filename = `${timestamp}_${randomString}${ext}`;
    cb(null, filename);
  }
});

// 音频文件上传配置
const audioUpload = multer({
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB
    files: 1
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['mp3', 'wav', 'm4a'];
    const validation = validateFileType(file, allowedTypes);
    if (validation.isValid) {
      cb(null, true);
    } else {
      cb(new Error(validation.message), false);
    }
  }
});

// 视频文件上传配置
const videoUpload = multer({
  storage: storage,
  limits: {
    fileSize: 50 * 1024 * 1024, // 50MB
    files: 1
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['mp4', 'mov'];
    const validation = validateFileType(file, allowedTypes);
    if (validation.isValid) {
      cb(null, true);
    } else {
      cb(new Error(validation.message), false);
    }
  }
});

// 图片文件上传配置
const imageUpload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB
    files: 1
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['jpg', 'jpeg', 'png'];
    const validation = validateFileType(file, allowedTypes);
    if (validation.isValid) {
      cb(null, true);
    } else {
      cb(new Error(validation.message), false);
    }
  }
});

/**
 * 上传音频文件
 * POST /upload/audio
 */
router.post('/audio', authenticateToken, audioUpload.single('file'), asyncHandler(async (req, res) => {
  const { type } = req.body;
  const file = req.file;
  const userId = req.user.id;

  if (!file) {
    return badRequest(res, '请选择要上传的音频文件');
  }

  // 验证文件类型参数
  if (type) {
    const typeValidation = validateEnum(type, ['detection', 'game', 'daily'], '文件类型');
    if (!typeValidation.isValid) {
      return badRequest(res, typeValidation.message);
    }
  }

  // 获取音频文件信息
  const audioInfo = await getAudioInfo(file.path);
  
  // 生成文件URL
  const baseUrl = process.env.BASE_URL || 'http://localhost:3000';
  const fileUrl = `${baseUrl}/uploads/audio/${file.filename}`;

  // 保存文件记录到数据库
  const fileRecord = await fileDao.createFileUpload({
    user_id: userId,
    original_name: file.originalname,
    filename: file.filename,
    file_path: file.path,
    file_url: fileUrl,
    file_size: file.size,
    mime_type: file.mimetype,
    usage_type: type || 'audio',
    metadata: JSON.stringify({
      duration: audioInfo.duration,
      format: audioInfo.format,
      bitrate: audioInfo.bitrate
    }),
    status: 'uploaded'
  });

  const responseData = {
    url: fileUrl,
    filename: file.filename,
    size: file.size,
    duration: audioInfo.duration,
    format: audioInfo.format,
    id: fileRecord.id
  };

  success(res, responseData, '音频文件上传成功');
}));

/**
 * 上传视频文件
 * POST /upload/video
 */
router.post('/video', authenticateToken, videoUpload.single('file'), asyncHandler(async (req, res) => {
  const { type } = req.body;
  const file = req.file;
  const userId = req.user.id;

  if (!file) {
    return badRequest(res, '请选择要上传的视频文件');
  }

  // 验证文件类型参数
  if (type) {
    const typeValidation = validateEnum(type, ['daily'], '文件类型');
    if (!typeValidation.isValid) {
      return badRequest(res, typeValidation.message);
    }
  }

  // 获取视频文件信息
  const videoInfo = await getVideoInfo(file.path);
  
  // 生成缩略图（可选）
  const thumbnailUrl = await generateVideoThumbnail(file.path, file.filename);
  
  // 生成文件URL
  const baseUrl = process.env.BASE_URL || 'http://localhost:3000';
  const fileUrl = `${baseUrl}/uploads/video/${file.filename}`;

  // 保存文件记录到数据库
  const fileRecord = await fileDao.createFileUpload({
    user_id: userId,
    original_name: file.originalname,
    filename: file.filename,
    file_path: file.path,
    file_url: fileUrl,
    file_size: file.size,
    mime_type: file.mimetype,
    usage_type: type || 'video',
    metadata: JSON.stringify({
      duration: videoInfo.duration,
      format: videoInfo.format,
      resolution: videoInfo.resolution,
      thumbnail: thumbnailUrl
    }),
    status: 'uploaded'
  });

  const responseData = {
    url: fileUrl,
    filename: file.filename,
    size: file.size,
    duration: videoInfo.duration,
    format: videoInfo.format,
    thumbnail: thumbnailUrl,
    id: fileRecord.id
  };

  success(res, responseData, '视频文件上传成功');
}));

/**
 * 上传图片文件
 * POST /upload/image
 */
router.post('/image', authenticateToken, imageUpload.single('file'), asyncHandler(async (req, res) => {
  const { type } = req.body;
  const file = req.file;
  const userId = req.user.id;

  if (!file) {
    return badRequest(res, '请选择要上传的图片文件');
  }

  // 验证文件类型参数
  if (type) {
    const typeValidation = validateEnum(type, ['avatar', 'content'], '文件类型');
    if (!typeValidation.isValid) {
      return badRequest(res, typeValidation.message);
    }
  }

  // 获取图片信息
  const imageInfo = await getImageInfo(file.path);
  
  // 生成文件URL
  const baseUrl = process.env.BASE_URL || 'http://localhost:3000';
  const fileUrl = `${baseUrl}/uploads/image/${file.filename}`;

  // 保存文件记录到数据库
  const fileRecord = await fileDao.createFileUpload({
    user_id: userId,
    original_name: file.originalname,
    filename: file.filename,
    file_path: file.path,
    file_url: fileUrl,
    file_size: file.size,
    mime_type: file.mimetype,
    usage_type: type || 'image',
    metadata: JSON.stringify({
      width: imageInfo.width,
      height: imageInfo.height,
      format: imageInfo.format
    }),
    status: 'uploaded'
  });

  const responseData = {
    url: fileUrl,
    filename: file.filename,
    size: file.size,
    width: imageInfo.width,
    height: imageInfo.height,
    format: imageInfo.format,
    id: fileRecord.id
  };

  success(res, responseData, '图片文件上传成功');
}));

/**
 * 获取文件信息
 * GET /upload/files/:id
 */
router.get('/files/:id', authenticateToken, asyncHandler(async (req, res) => {
  const { id } = req.params;
  const userId = req.user.id;
  
  if (!id || isNaN(parseInt(id))) {
    return badRequest(res, '无效的文件ID');
  }

  const fileRecord = await fileDao.getFileUploadById(parseInt(id));
  
  if (!fileRecord) {
    return notFound(res, '文件不存在');
  }

  // 检查是否为当前用户的文件
  if (fileRecord.user_id !== userId) {
    return forbidden(res, '无权访问此文件');
  }

  const fileInfo = {
    id: fileRecord.id,
    originalName: fileRecord.original_name,
    filename: fileRecord.filename,
    url: fileRecord.file_url,
    size: fileRecord.file_size,
    mimeType: fileRecord.mime_type,
    usageType: fileRecord.usage_type,
    metadata: fileRecord.metadata ? JSON.parse(fileRecord.metadata) : null,
    status: fileRecord.status,
    createdAt: fileRecord.created_at
  };

  success(res, fileInfo);
}));

// 辅助函数：获取音频信息
async function getAudioInfo(filePath) {
  try {
    // TODO: 使用音频处理库获取实际信息
    // 这里返回模拟数据
    return {
      duration: 30, // 秒
      format: 'mp3',
      bitrate: 128 // kbps
    };
  } catch (error) {
    console.error('获取音频信息失败:', error);
    return {
      duration: 0,
      format: 'unknown',
      bitrate: 0
    };
  }
}

// 辅助函数：获取视频信息
async function getVideoInfo(filePath) {
  try {
    // TODO: 使用视频处理库获取实际信息
    // 这里返回模拟数据
    return {
      duration: 60, // 秒
      format: 'mp4',
      resolution: '1920x1080'
    };
  } catch (error) {
    console.error('获取视频信息失败:', error);
    return {
      duration: 0,
      format: 'unknown',
      resolution: '0x0'
    };
  }
}

// 辅助函数：获取图片信息
async function getImageInfo(filePath) {
  try {
    // TODO: 使用图片处理库获取实际信息
    // 这里返回模拟数据
    return {
      width: 800,
      height: 600,
      format: 'jpeg'
    };
  } catch (error) {
    console.error('获取图片信息失败:', error);
    return {
      width: 0,
      height: 0,
      format: 'unknown'
    };
  }
}

// 辅助函数：生成视频缩略图
async function generateVideoThumbnail(videoPath, filename) {
  try {
    // TODO: 使用视频处理库生成缩略图
    // 这里返回模拟URL
    const baseUrl = process.env.BASE_URL || 'http://localhost:3000';
    return `${baseUrl}/uploads/thumbnails/${filename.replace(/\.[^/.]+$/, '')}_thumb.jpg`;
  } catch (error) {
    console.error('生成视频缩略图失败:', error);
    return null;
  }
}

module.exports = router;
